package com.project.controller.activity;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.dtyunxi.rest.RestResponse;
import com.project.controller.BaseController;
import com.project.entity.activity.Activity;
import com.project.entity.activity.ActivityLog;
import com.project.entity.activity.ActivityUser;
import com.project.entity.enumcommon.AuditStatusEnum;
import com.project.entity.sms.SmsMessageVo;
import com.project.entity.user.Member;
import com.project.service.activity.ActivityService;
import com.project.service.activitylog.ActivityLogService;
import com.project.service.activityuser.ActivityUserService;
import com.project.service.sms.SmsService;
import com.project.service.user.MemberService;
import com.project.util.CurrentSessionUtil;

@Controller
@RequestMapping("/activity/user")
public class ActivityUserController extends BaseController<ActivityUser>{
	
	@Autowired
	private ActivityUserService activityUserService;
	@Autowired
	private SmsService smsService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private ActivityLogService activityLogService;
	
	
	@RequestMapping("list")
	public String list(Model model,@ModelAttribute ActivityUser activityUser) {
		if(activityUser.getActivityId()!=null){
			model.addAttribute("entity", activityUser);
			model.addAttribute("list", service.query(activityUser));
		}
		return "/activity/user/list";
	}
	
	
	@RequestMapping("view")
	public String view(Model model) {
		model.addAttribute("entity", getEntity());
		Member member = new Member();
		member.setUserId(getEntity().getUserId());
		model.addAttribute("member", memberService.queryEntity(member));
		return "/activity/user/view";
	}
	
	
	@RequestMapping("updateAudit")
    @ResponseBody
    public String updateAudit(Model model,String id,String auditDescription,String auditStatus){
	    ActivityUser activityUser =  service.getById(getClazz(), Long.valueOf(id));
	    activityUser.setAuditDescription(auditDescription);
	    activityUser.setAuditStatus(AuditStatusEnum.getInstance(auditStatus));
	    activityUser.setAuditTime(new Date());
	    activityUser.setAuditUser(CurrentSessionUtil.getCurrentUser().getUserCode());
        service.update(activityUser);
        //保存日志
        ActivityLog activityLog = new ActivityLog();
        activityLog.setActivityUserId(Long.valueOf(id));
        activityLog.setActivityId(activityUser.getActivityId());
        activityLog.setCreateTime(new Date());
        activityLog.setCreateUser(CurrentSessionUtil.getCurrentUser().getUserCode());
        activityLog.setStatus(AuditStatusEnum.getInstance(auditStatus));
        activityLog.setContent(AuditStatusEnum.getInstance(auditStatus).getValue()+"审核");
        activityLogService.save(activityLog);
        sendSms(activityUser, auditDescription, auditStatus);
        return "true";
    }
	
	@Async
	private void sendSms(ActivityUser activityUser, String auditDescription, String auditStatus) {
		Activity activity = activityService.getById(Activity.class,activityUser.getActivityId());
		if(activity!=null){
			String activityName = activity.getName();
			//尊敬的{1}先生/女士，您报名的“{3}”活动已审核，结果为：{6}。相关说明：{8}。
			SmsMessageVo smsMessageVo = new SmsMessageVo();
			smsMessageVo.setTaget(activityUser.getMobile());
			smsMessageVo.setSendPoint("SMS_SEND_ACTIVITY_USER_AUDIT");
			smsMessageVo.addValue("username", activityUser.getName());
			smsMessageVo.addValue("servicename", activityName);
			smsMessageVo.addValue("reason", auditStatus);
			smsMessageVo.addValue("other", auditDescription);
			smsService.sendSms(smsMessageVo);
		}
		
	}


	@RequestMapping("update")
	public String update(Model model){
	    model.addAttribute("entity", getEntity());
	    Member member = new Member();
        member.setUserId(getEntity().getUserId());
        model.addAttribute("member", memberService.queryEntity(member));
        return "/activity/user/update";
	}
	
	@RequestMapping("save")
    @ResponseBody
    public String save(Model model,@ModelAttribute(name="entity") ActivityUser activityUser){
        activityUser.setUpdateTime(new Date());
        activityUser.setUpdateUser(CurrentSessionUtil.getCurrentUser().getUserCode());
        service.update(activityUser);
        return "true";
    }
	
	/**
	 * 下载表格
	 * @param pianoTuner
	 * @return
	 */
	@RequestMapping(value = "download",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public String downloadReport(@ModelAttribute ActivityUser activityUser,HttpServletResponse response,HttpServletRequest request){
		if(activityUser != null && activityUser.getActivityId() != null ){
			List<ActivityUser> queryList = service.query(activityUser);
			
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			Map<String, Object> sheetName = new HashMap<String, Object>();
			sheetName.put("sheetName", "活动报名审批");
			list.add(sheetName);
			for(ActivityUser au:queryList){
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("userCode", au.getUserCode());
				map.put("name", au.getName());
				map.put("position", au.getPosition());
				if(au.getProvinceEntity() != null && au.getCityEntity() != null){
					map.put("addr", au.getProvinceEntity().getName()+" "+au.getCityEntity().getName());
				}else{
					map.put("addr", "");
				}
				map.put("auditStatus", au.getAuditStatus().getValue());
				map.put("auditDescription", au.getAuditDescription());
				map.put("cancelReason", au.getCancelReason());
				
				list.add(map);
			}
			
			String fileName = "";
			try {
				fileName = this.encodeChineseDownloadFileName(request, "活动报名审批");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			activityUserService.downloadExcel(fileName,list,response);
			RestResponse jsonBean = new RestResponse(0,"下载成功！","");
			return JSONObject.toJSONString(jsonBean);
		}else{
			RestResponse jsonBean = new RestResponse(0,"数据为空！","");
			return JSONObject.toJSONString(jsonBean);
		}
		
	}
	
	 /**
	  * 解决下载文件名中文乱码
	  * @param request
	  * @param pFileName
	  * @return
	  * @throws UnsupportedEncodingException
	  */
	 public static String encodeChineseDownloadFileName(  
	            HttpServletRequest request, String pFileName) throws UnsupportedEncodingException {  
	         String filename = null;    
	            String agent = request.getHeader("USER-AGENT");    
	            if (null != agent){    
	                if (-1 != agent.indexOf("Firefox")) {//Firefox    
	                    filename = "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes("UTF-8"))))+ "?=";    
	                }else if (-1 != agent.indexOf("Chrome")&&-1==agent.indexOf("Edge")) {//Chrome    
	                    filename = new String(pFileName.getBytes(), "ISO8859-1");     
	                } else {//IE7+    
	                    filename = java.net.URLEncoder.encode(pFileName, "UTF-8");    
	                    filename = StringUtils.replace(filename, "+", "%20");//替换空格    
	                }    
	            } else {    
	                filename = pFileName;    
	            }    
	            return filename;   
	    } 
	 
	
	@Override
	protected Class<ActivityUser> getClazz() {
		return ActivityUser.class;
	}

}
